package com.xu.system.auth.code;

import com.xu.security.model.OnlineUser;
import com.xu.security.token.TokenService;
import jakarta.annotation.Resource;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * 工号认证器
 *
 * @Author: 许乾伟
 * @Date: 2024/12/5 14:41
 */
@Component
public class CodeAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private CodeUserDetailsService codeUserDetailsService;

    @Resource
    TokenService tokenService;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        CodeAuthenticationToken codeToken = (CodeAuthenticationToken) authentication;
        String account = codeToken.getPrincipal().toString();
        OnlineUser userDetails = (OnlineUser) codeUserDetailsService.loadUserByUsername(account);
        //创建token
        tokenService.createToken(userDetails);
        return new CodeAuthenticationToken(userDetails,userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        //指定认证器支持的认证类型
        return authentication.equals(CodeAuthenticationToken.class);
    }
}
